package com.arpa.wms.controller.wms;

import cn.hutool.core.collection.IterUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.dto.ExpenseDetailDTO;
import com.arpa.wms.domain.dto.ExpenseDetailSettlementDTO;
import com.arpa.wms.domain.entity.ExpenseDetail;
import com.arpa.wms.domain.vo.ExpenseDetailVO;
import com.arpa.wms.service.IExpenseDetailService;
import com.arpa.wms.service.IReceiptService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;


/**
 * <p>
 * 仓库费用明细 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "仓库费用明细")
@RestController
@RequestMapping(value = "/expenseDetail", produces = "application/json;charset=UTF-8")
@Log4j2
public class ExpenseDetailController {

    private final IExpenseDetailService iExpenseDetailService;

    private final IReceiptService receiptService;


    @Resource
    private RedissonClient redissonClient;

    public ExpenseDetailController(IExpenseDetailService iExpenseDetailService, IReceiptService receiptService) {
        this.iExpenseDetailService = iExpenseDetailService;
        this.receiptService = receiptService;
    }

    /**
     * 获取 仓库费用明细 列表
     *
     * @param expenseDetailDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 仓库费用明细 列表", notes = "获取 仓库费用明细 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer ")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ExpenseDetailVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(ExpenseDetailDTO expenseDetailDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            expenseDetailDTO.setGroupCode(UserUtil.getBranchCode());
            //登录账号授权的仓库过滤
            expenseDetailDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤
            expenseDetailDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            ExpenseDetailVO expenseDetailVOSum = iExpenseDetailService.queryListSum(expenseDetailDTO);
            List<ExpenseDetailVO> expenseDetailVOList = iExpenseDetailService.queryList(expenseDetailDTO);

            Page returnPage = new Page(expenseDetailDTO.getPageNum(), expenseDetailDTO.getPageSize());
            returnPage.setRecords(expenseDetailVOList);
            returnPage.setTotal(expenseDetailVOSum.getTotal());
            returnPage.setSumObject(expenseDetailVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 仓库费用明细
     * TODO 用于Arpa-Cloud调度系统定时调用生成仓库费用明细
     *
     * @return
     */
    @ApiOperation(value = "生成仓库费用记录", notes = "用于Arpa-Cloud调度系统定时调用生成仓库费用明细")
    @GetMapping("/generate")
    public void generate( @RequestParam(value = "groupCode",defaultValue = "") String groupCode) {
        try {
            log.info("Arpa-Cloud调度系统调用生成仓库费用明细");
            iExpenseDetailService.generate(groupCode);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
        }
    }

    /**
     * 获取仓库费用明细详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取仓库费用明细详情", notes = "获取仓库费用明细详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库费用明细code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ExpenseDetail.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result expenseDetail(@PathVariable String code, HttpServletRequest request) {
        try {
            ExpenseDetail expenseDetail = iExpenseDetailService.getOne(new QueryWrapper<ExpenseDetail>().lambda().eq(ExpenseDetail::getCode, code).eq(ExpenseDetail::getGroupCode,UserUtil.getBranchCode()));
            return Result.ok().data(expenseDetail);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改仓库费用明细
     *
     * @param amount  仓库费用金额
     * @param request
     * @return
     */
    @ApiOperation(value = "修改费用明细", notes = "修改仓库费用明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库费用明细标识", paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "amount", value = "仓库费用金额，必须大于等于0", paramType = "query", dataType = "double"),
            @ApiImplicitParam(name = "remarks", value = "备注", paramType = "query", dataType = "String"),
    })
    @NeedLogin
    @PutMapping(value = "/{code}")
    public Result update(@PathVariable String code, @RequestParam(value = "amount") BigDecimal amount, @RequestParam(value = "remarks", required = false) String remarks, HttpServletRequest request) {
        boolean updateNum = iExpenseDetailService.updateAmount(code, amount, remarks);
        if (updateNum) {
            return Result.ok("费用修改成功！");
        }
        return Result.error("费用修改失败！");
    }

    /**
     * 删除 仓库费用明细
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 仓库费用明细 ", notes = "删除 仓库费用明细 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "code", value = "仓库费用明细code", paramType = "path", dataType = "String")
    })
    @NeedLogin
    @DeleteMapping(value = "/{code}")
    public Result remove(@PathVariable String code, HttpServletRequest request) {
        try {
            boolean bool = iExpenseDetailService.removeByCode(code);
            if (bool) {
                return Result.ok("费用删除成功！");
            }
            return Result.error("费用删除失败！");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 仓库费用结算
     *
     * @param settlement
     * @param request
     * @return
     */
    @ApiOperation(value = "仓库费用结算 ", notes = "仓库费用结算", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
    })
    @NeedLogin
    @PostMapping(value = "/settlement")
    public Result settlement(@RequestBody @Validated ExpenseDetailSettlementDTO settlement, HttpServletRequest request) {

        List<RLock> locks = Lists.newArrayList();
        List<String> failCodes = Lists.newArrayList();
        String failMsg = "";
        String groupCode = UserUtil.getBranchCode();
        try {
            //可操作的CODE
            List<ExpenseDetailSettlementDTO.SettlementItem> execCodes = Lists.newArrayList();
            List<ExpenseDetailSettlementDTO.SettlementItem> items = settlement.getSettlementItems();
            if (IterUtil.isEmpty(items)) {
                return Result.error("请选择结算费用");
            }
            for (ExpenseDetailSettlementDTO.SettlementItem item : items) {
                RLock l = redissonClient.getLock(getSettlementLockKey(item.getCode()));
                if (l.tryLock()) {
                    log.info("结算费用【{}】获得锁", item.getCode());
                    execCodes.add(item);
                    locks.add(l);
                } else {
                    failCodes.add(item.getCode());
                    failMsg = "结算费用【" + item.getCode() + "】正在操作中";
                    log.error("结算费用【{}】正在操作中", item.getCode());
                }
            }


            // 失败的订单集合
            // 线程结果集
            Map<String, Future<Boolean>> futureMap = Maps.newHashMap();
            for (ExpenseDetailSettlementDTO.SettlementItem item  : execCodes) {
                Future future = iExpenseDetailService.check(item,groupCode);
                if (future == null) {
                    failCodes.add(item.getCode());
                } else {
                    futureMap.put(item.getCode(), future);
                }
            }

            Iterator<Map.Entry<String, Future<Boolean>>> iterator = futureMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Future<Boolean>> entry = iterator.next();
                try {
                    Boolean status = entry.getValue().get();
                    if (!status) {
                        failCodes.add(entry.getKey());
                    }
                } catch (ServiceException e) {
                    log.error("结算费用【{}】线程获取结果【{}】", entry.getKey(), e.getMessage());
                    failMsg += "<br/><font color='red'>" + e.getMessage() + ";</font>";
                    failCodes.add(entry.getKey());
                } catch (Exception e) {
                    log.error("结算费用【{}】线程获取结果【{}】", entry.getKey(), e.getMessage());
                    failMsg += "<br/><font color='red'>" + e.getCause().getMessage() + ";</font>";
                    failCodes.add(entry.getKey());
                }
            }

            if (failCodes.size() > 0) {
                return Result.error("费用结算失败:" + failMsg);
            } else {
                receiptService.settlement(settlement);
            }
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }  finally {
            try {
                locks.forEach(l -> {
                    // 判断锁不为空 && 当前线程获得到了锁
                    if (null != l && l.isLocked()) {
                        l.unlock();
                    }
                });
            } catch (Exception e) {
                log.error("释放锁失败！！", e);
            }

        }

        return Result.ok("费用结算成功");
    }

    /**
     * 费用结算分布式锁
     *
     * @param code
     * @return
     */
    private String getSettlementLockKey(String code) {
        return String.format("settlement-code-%s", code);
    }

}
